import React, { useState } from 'react'
import {
  Table,
  Card,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Switch,
  Tag,
  message,
  Popconfirm,
  Divider,
  Row,
  Col,
  Tree,
  Transfer,
  Typography
} from 'antd'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  TeamOutlined,
  SecurityScanOutlined,
  UserAddOutlined
} from '@ant-design/icons'

const { Title } = Typography
const { TextArea } = Input

// 模拟角色数据
const initialRoles = [
  {
    id: 1,
    name: '超级管理员',
    code: 'super_admin',
    description: '拥有系统所有权限',
    status: true,
    createTime: '2023-01-15 10:30:00',
    userCount: 3
  },
  {
    id: 2,
    name: '系统管理员',
    code: 'admin',
    description: '拥有系统管理权限',
    status: true,
    createTime: '2023-02-20 14:20:00',
    userCount: 5
  },
  {
    id: 3,
    name: '普通用户',
    code: 'user',
    description: '普通使用权限',
    status: true,
    createTime: '2023-03-10 09:15:00',
    userCount: 156
  },
  {
    id: 4,
    name: '访客',
    code: 'guest',
    description: '只读权限',
    status: false,
    createTime: '2023-04-05 16:45:00',
    userCount: 24
  }
]

// 模拟权限数据
const permissionData = [
  {
    key: 'system',
    title: '系统管理',
    children: [
      {
        key: 'system:user',
        title: '用户管理',
        children: [
          { key: 'system:user:view', title: '查看用户' },
          { key: 'system:user:add', title: '新增用户' },
          { key: 'system:user:edit', title: '编辑用户' },
          { key: 'system:user:delete', title: '删除用户' }
        ]
      },
      {
        key: 'system:role',
        title: '角色管理',
        children: [
          { key: 'system:role:view', title: '查看角色' },
          { key: 'system:role:add', title: '新增角色' },
          { key: 'system:role:edit', title: '编辑角色' },
          { key: 'system:role:delete', title: '删除角色' }
        ]
      }
    ]
  },
  {
    key: 'content',
    title: '内容管理',
    children: [
      {
        key: 'content:article',
        title: '文章管理',
        children: [
          { key: 'content:article:view', title: '查看文章' },
          { key: 'content:article:add', title: '新增文章' },
          { key: 'content:article:edit', title: '编辑文章' },
          { key: 'content:article:delete', title: '删除文章' },
          { key: 'content:article:publish', title: '发布文章' }
        ]
      },
      {
        key: 'content:category',
        title: '分类管理',
        children: [
          { key: 'content:category:view', title: '查看分类' },
          { key: 'content:category:add', title: '新增分类' },
          { key: 'content:category:edit', title: '编辑分类' },
          { key: 'content:category:delete', title: '删除分类' }
        ]
      }
    ]
  }
]

// 模拟用户数据
const mockUsers = Array.from({ length: 20 }, (_, i) => ({
  key: i.toString(),
  name: `用户${i + 1}`,
  department: i % 3 === 0 ? '技术部' : i % 3 === 1 ? '市场部' : '运营部'
}))

const Index: React.FC = () => {
  const [roles, setRoles] = useState(initialRoles)
  const [modalVisible, setModalVisible] = useState(false)
  const [permissionModalVisible, setPermissionModalVisible] = useState(false)
  const [userModalVisible, setUserModalVisible] = useState(false)
  const [editingRole, setEditingRole] = useState(null)
  const [form] = Form.useForm()
  const [permissionForm] = Form.useForm()
  const [selectedRole, setSelectedRole] = useState(null)
  const [targetKeys, setTargetKeys] = useState(['0', '2', '5'])

  // 表格列定义
  const columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <span>
          <TeamOutlined style={{ marginRight: 8, color: '#1890ff' }} />
          {text}
        </span>
      )
    },
    {
      title: '角色编码',
      dataIndex: 'code',
      key: 'code',
      render: text => <Tag color='blue'>{text}</Tag>
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: status => (
        <Tag color={status ? 'green' : 'red'}>{status ? '启用' : '禁用'}</Tag>
      )
    },
    {
      title: '用户数',
      dataIndex: 'userCount',
      key: 'userCount',
      render: count => (
        <Button
          type='link'
          icon={<UserAddOutlined />}
          onClick={() => showUserModal(selectedRole)}
        >
          {count}人
        </Button>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size='middle'>
          <Button
            type='link'
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type='link'
            icon={<SecurityScanOutlined />}
            onClick={() => showPermissionModal(record)}
          >
            权限
          </Button>
          <Popconfirm
            title='确定要删除这个角色吗？'
            onConfirm={() => handleDelete(record.id)}
            okText='确定'
            cancelText='取消'
          >
            <Button type='link' danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]

  // 显示权限配置模态框
  const showPermissionModal = role => {
    setSelectedRole(role)
    setPermissionModalVisible(true)
  }

  // 显示用户分配模态框
  const showUserModal = role => {
    setSelectedRole(role)
    setUserModalVisible(true)
  }

  // 显示新增/编辑模态框
  const showModal = (role = null) => {
    setEditingRole(role)
    if (role) {
      form.setFieldsValue(role)
    } else {
      form.resetFields()
    }
    setModalVisible(true)
  }

  // 处理表单提交
  const handleSubmit = values => {
    if (editingRole) {
      // 编辑角色
      setRoles(
        roles.map(role =>
          role.id === editingRole.id ? { ...editingRole, ...values } : role
        )
      )
      message.success('角色更新成功')
    } else {
      // 新增角色
      const newRole = {
        id: Math.max(...roles.map(r => r.id)) + 1,
        ...values,
        userCount: 0,
        createTime: new Date().toLocaleString()
      }
      setRoles([...roles, newRole])
      message.success('角色创建成功')
    }
    setModalVisible(false)
  }

  // 删除角色
  const handleDelete = id => {
    setRoles(roles.filter(role => role.id !== id))
    message.success('角色删除成功')
  }

  // 处理权限配置
  const handlePermissionSubmit = values => {
    console.log('权限配置:', values)
    message.success('权限配置已更新')
    setPermissionModalVisible(false)
  }

  // 处理用户分配
  const handleUserChange = nextTargetKeys => {
    setTargetKeys(nextTargetKeys)
  }

  const handleUserSubmit = () => {
    message.success('用户分配已更新')
    setUserModalVisible(false)
  }

  // 权限树渲染
  const renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <Tree.TreeNode key={item.key} title={item.title}>
            {renderTreeNodes(item.children)}
          </Tree.TreeNode>
        )
      }
      return <Tree.TreeNode key={item.key} title={item.title} />
    })

  return (
    <div className='role-management'>
      <Card>
        <div
          style={{
            marginBottom: 16,
            display: 'flex',
            justifyContent: 'space-between'
          }}
        >
          <Title level={3} style={{ margin: 0 }}>
            <TeamOutlined style={{ marginRight: 12 }} />
            角色管理
          </Title>
          <Button
            type='primary'
            icon={<PlusOutlined />}
            onClick={() => showModal()}
          >
            新增角色
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={roles}
          rowKey='id'
          pagination={{
            total: roles.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: total => `共 ${total} 条记录`
          }}
        />
      </Card>

      {/* 新增/编辑角色模态框 */}
      <Modal
        title={editingRole ? '编辑角色' : '新增角色'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form form={form} layout='vertical' onFinish={handleSubmit}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name='name'
                label='角色名称'
                rules={[{ required: true, message: '请输入角色名称' }]}
              >
                <Input placeholder='请输入角色名称' />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name='code'
                label='角色编码'
                rules={[{ required: true, message: '请输入角色编码' }]}
              >
                <Input placeholder='请输入角色编码' />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name='description' label='角色描述'>
            <TextArea rows={3} placeholder='请输入角色描述' />
          </Form.Item>
          <Form.Item name='status' label='状态' valuePropName='checked'>
            <Switch checkedChildren='启用' unCheckedChildren='禁用' />
          </Form.Item>
          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => setModalVisible(false)}>取消</Button>
              <Button type='primary' htmlType='submit'>
                {editingRole ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 权限配置模态框 */}
      <Modal
        title={`权限配置 - ${selectedRole?.name}`}
        open={permissionModalVisible}
        onCancel={() => setPermissionModalVisible(false)}
        footer={null}
        width={700}
      >
        <Form
          form={permissionForm}
          layout='vertical'
          onFinish={handlePermissionSubmit}
        >
          <Form.Item name='permissions' label='权限分配'>
            <Tree
              checkable
              defaultExpandAll
              defaultCheckedKeys={['system:user:view', 'system:user:add']}
            >
              {renderTreeNodes(permissionData)}
            </Tree>
          </Form.Item>
          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => setPermissionModalVisible(false)}>
                取消
              </Button>
              <Button type='primary' htmlType='submit'>
                保存权限
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 用户分配模态框 */}
      <Modal
        title={`用户分配 - ${selectedRole?.name}`}
        open={userModalVisible}
        onCancel={() => setUserModalVisible(false)}
        footer={null}
        width={800}
      >
        <Transfer
          dataSource={mockUsers}
          targetKeys={targetKeys}
          onChange={handleUserChange}
          render={item => `${item.name} - ${item.department}`}
          listStyle={{
            width: 300,
            height: 400
          }}
          operations={['分配', '移除']}
          titles={['所有用户', '已分配用户']}
        />
        <Divider />
        <div style={{ textAlign: 'right', marginTop: 16 }}>
          <Space>
            <Button onClick={() => setUserModalVisible(false)}>取消</Button>
            <Button type='primary' onClick={handleUserSubmit}>
              保存分配
            </Button>
          </Space>
        </div>
      </Modal>
    </div>
  )
}

export default Index
